package com.offcn.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtil {

    // 有效期
    public static final long JWT_EXP = 3600000L;
    // jwt的令牌信息
    public static final String JWT_SECRET = "secret";


    /**
     * 生成密钥
     */
    public static String createJwt(String id,String subject,Long expTime){
        // 指定算法
        SignatureAlgorithm sign = SignatureAlgorithm.HS256;
        // 获取当前系统时间
        long millis = System.currentTimeMillis();
        // 令牌的签发时间
        Date date = new Date(millis);
        if (expTime == null){
            expTime = JWT_EXP;
        }
        long expMills = millis + expTime;
        Date expDate = new Date(expMills);
        // 生成密钥
        SecretKey secretKey = registerJwt();
        // 封装jwt
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuer("admin")
                .setIssuedAt(date)
                .setExpiration(expDate)
                .signWith(sign, secretKey);
        return builder.compact();
    }

    public  static SecretKey registerJwt() {
        byte[] encode = Base64.getEncoder().encode(JwtUtil.JWT_SECRET.getBytes());
        SecretKeySpec spec = new SecretKeySpec(encode, 0, encode.length, "AES");
        return spec;
    }

    /**
     * 解析密钥
     */
    public static Claims  parseJwt(String jwt){
        SecretKey key = registerJwt();
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
